//
//  OAuthViewController.swift
//  个人微博
//
//  Created by guo3920591 on 16/4/19.
//  Copyright © 2016年 guo3920591. All rights reserved.
//

import UIKit
import SVProgressHUD

let app_key = "1193457754"
let appSecret = "28d790af136d192ec37980ac2dfa5a10"
let redirect_uri = "http://www.baidu.com"



class OAuthViewController: UIViewController {
    
 private lazy var webView: UIWebView = {
        
        let webview = UIWebView()
        
        webview.delegate = self
        
      
        
        return webview
        
    }()
    
    /// 视图生命周期
    override func loadView() {
        view = webView
        //加载webView
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
     
        
        setupUI()

        
    }


    
/// 设置UI界面
    private func setupUI(){
        
        //在纯代码开发的时候 必须制定view的背景色
        view.backgroundColor = UIColor.whiteColor()
        
        title = "登陆微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
        
        
    }
    
    @objc private func cancel(){
        
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func autoFill(){
        
        
        let strUrl = "document.getElementById('userId').value='18721831867';document.getElementById('passwd').value='ys815812213'"
        
        webView.stringByEvaluatingJavaScriptFromString(strUrl)
        
        
        
    }
    
}
    
   
  

 


extension OAuthViewController: UIWebViewDelegate {
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //print(request.URL?.host)
        
        guard let urlStr = request.URL else {
            
            return false
        }
        
       //如果不是以回调页开头就继续加载页面
        if !urlStr.absoluteString.hasPrefix(NetworkTools.sharedTools.redirect_uri){
            
            return true
        }
        
       //判断query是否包含code=
        
        if let query = request.URL?.query where query.hasPrefix("code=") {
          
            let code = query.substringFromIndex("code=".endIndex)
            
            //发起网络请求
            
            NetworkTools.sharedTools.loadAccessToken(code, finished: { (result) -> () in
                
                guard let result = result else {
                    
                    
                    print("你的网络不给力")
                    return
                }
               
                 /// 创建用户账户单利的数据
      OAuthModel.shareUserAccount.upDataWithDict(result)
                
                //登录成功 发布通知
                
                NSNotificationCenter.defaultCenter().postNotificationName(GXLWeiboLoginSuccessNofication, object: nil)
                
                
            SVProgressHUD.showInfoWithStatus("登录成功")
               
                
                dispatch_after(
                    dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1.0)),
                    dispatch_get_main_queue(), { () -> Void in
                        
                        //关闭视图
                        self.dismissViewControllerAnimated(true, completion: nil)
                })
                
                
                
                
                
            })
            
            
            
            
            return false
          
        
        }
            
            print("取消授权")
        
        dismissViewControllerAnimated(true, completion: nil)
       
        
    
        return false
        
    }
    
    
    
}
    
    

